//package com.topisv.tms.utils.http;
//
//import java.text.SimpleDateFormat;
//import java.util.Date;
//import java.util.Map;
//import java.util.TreeMap;
//
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.context.ApplicationContext;
//import org.springframework.context.ApplicationContextAware;
//import org.springframework.orm.hibernate4.HibernateOptimisticLockingFailureException;
//import org.springframework.stereotype.Component;
//
//import com.topisv.tms.api.EdbAPITool;
//import com.topisv.tms.entity.Area;
//import com.topisv.tms.entity.EdiOrder;
//import com.topisv.tms.entity.ShopSource;
//import com.topisv.tms.entity.edb.EdbTask;
//import com.topisv.tms.service.AreaService;
//import com.topisv.tms.service.EdiOrderService;
//import com.topisv.tms.service.ShopSourceService;
//import com.topisv.tms.service.edb.EdbTaskService;
//import com.topisv.tms.utils.TimeUtil;
//
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
//
//@Component
//public class SynchroEdbTradeGet implements Runnable,ApplicationContextAware  {
//	private String customerCode="SUN";
//	private String warehouseCode="GZ";
//	
//	
//	private static final Logger log = LoggerFactory.getLogger(SynchroEdbTradeGet.class);
//	
//	private static final int SLEEP_TIME=2*1000;//本现场扫描间隔时间，必须小于任务的间隔时间
//	public final static int DEDAULT_INTERVAL_TIME = 60 * 1000;
//	public final static int SYS_DIFF_TIME = 5*60*1000; // 由于对接系统间数据处理不可能做到实时同步，为了避免出现抓漏需要有一个时间差
//	
//	@Autowired
//	private EdbTaskService edbTaskService;
//	
//	public  SynchroEdbTradeGet( ){
//		this("SUN","GZ");
//	}
//	
//	public  SynchroEdbTradeGet(String customerCode,String warehouseCode ){
//		this.customerCode = customerCode;
//		this.warehouseCode = warehouseCode;
//	}
//	public EdbTaskService getEdbTaskService() {
//		if(edbTaskService==null)edbTaskService = (EdbTaskService)applicationContext.getBean("edbTaskService");
//		return edbTaskService;
//	}
//
//	public EdiOrderService getEdiOrderService() {
//		if(ediOrderService==null)ediOrderService = (EdiOrderService)applicationContext.getBean("ediOrderService");
//		return ediOrderService;
//	}
//
//	public ShopSourceService getShopSourceService() {
//		if(shopSourceService==null)shopSourceService = (ShopSourceService)applicationContext.getBean("shopSourceService");
//		return shopSourceService;
//	}
//
//	public AreaService getAreaService() {
//		if(areaService==null)areaService = (AreaService)applicationContext.getBean("areaService");
//		return areaService;
//	}
//	@Autowired
//	private EdiOrderService ediOrderService;
//	@Autowired
//	private ShopSourceService shopSourceService;
//	@Autowired
//	private AreaService areaService;
//	
//	private volatile boolean flag=true;
//	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//	@Override
//	public synchronized void run() {
//		int intervalTime =DEDAULT_INTERVAL_TIME;
//		int threadIntervalTime =SLEEP_TIME;
//		int sysDiffTime =SYS_DIFF_TIME;
//		boolean stop=false;
//		EdbTask edbTask = null;
//		while(flag){
//				try {
//					Thread.currentThread().sleep(threadIntervalTime);
//					edbTask = getEdbTaskService().findTask(customerCode, warehouseCode, "edbTradeGet");
//					if(edbTask != null ){
////						log.info("任务起始时间："+df.format(edbTask.getStartTime())+" - 终止时间："+df.format(edbTask.getEndTime())+" 刷单间隔:"+edbTask.getIntervalTime()+" 定时间隔："+edbTask.getThreadIntervalTime()/1000+"秒，系统时间差间隔: "+ edbTask.getSysDiffTime()/1000+"秒");
//
//						if("0".equals(edbTask.getStatus())){
//							if(!stop){
//								stop =true;
//								log.info(customerCode+"-"+warehouseCode+"-edbTradeGet task is stoped.");
//							} 
//							continue;
//						}
//						
//						stop =false;
//						Date endDate=edbTask.getEndTime();
//						int inTime =DEDAULT_INTERVAL_TIME;
//						try {
//							inTime = Integer.parseInt(edbTask.getIntervalTime());
//							
//						}  catch (NumberFormatException e) {
////							log.error("E店宝接口配置异常："+customerCode+"-"+warehouseCode+"-edbTradeGet :订单间隔时间数值非整形:" +edbTask.getIntervalTime()  );
//						}
//						intervalTime = inTime >0 ? inTime : DEDAULT_INTERVAL_TIME;
//						threadIntervalTime =  edbTask.getThreadIntervalTime()>0 &&  edbTask.getThreadIntervalTime()< intervalTime ? edbTask.getThreadIntervalTime() :SLEEP_TIME;
//						sysDiffTime = edbTask.getSysDiffTime()>0 ? edbTask.getSysDiffTime() : SYS_DIFF_TIME;
//						
//						long now = System.currentTimeMillis() - sysDiffTime ;
//						if( now < endDate.getTime()){
//							if(now >= edbTask.getStartTime().getTime()){
//								// 把某段时间开始到现在的单刷一遍
//								edbTask.setEndTime(new Date(now-threadIntervalTime)); // 减去睡眠间隔保证下面保存后数据只用一次，否则会循环intervalTime/threadIntervalTime 次
//								getEdbTaskService().save(edbTask);
//								log.info("E店宝重刷订单开始时间："+df.format(edbTask.getStartTime())+" - 结束时间："+df.format(edbTask.getEndTime())+" 每次取"+intervalTime/1000+"秒的数据，轮询间隔："+threadIntervalTime/1000+"秒，对接系统时间余量: "+ sysDiffTime/1000+"秒");
//								doSyncTrade(edbTask,"1");
//							} else { 
//								// 没到开始时间
//							}
//							continue;
//						} else if(now - endDate.getTime() < intervalTime){
//							// 最小间隔没到
//							continue;
//						} 
//						log.info("最后订单时间："+df.format(endDate));
//						edbTask.setStartTime(endDate);
//						endDate =new Date(now);
//						edbTask.setEndTime(endDate);
//						getEdbTaskService().save(edbTask);
//						log.info("E店宝订单开始时间："+df.format(edbTask.getStartTime())+" - 结束时间："+df.format(edbTask.getEndTime())+" 每次取"+intervalTime/1000+"秒的数据，轮询间隔："+threadIntervalTime/1000+"秒，对接系统时间余量: "+ sysDiffTime/1000+"秒");
//						doSyncTrade(edbTask,"1");
//					} else {
////						log.error("E店宝配置不存在："+customerCode+"-"+warehouseCode+"-edbTradeGet");
//					}
//				}catch (InterruptedException e) {
//					log.error("E店宝程序中断:"+customerCode+"-"+warehouseCode+"-edbTradeGet", e);
//				} catch (HibernateOptimisticLockingFailureException e) {
//					log.error("E店宝程序乐观锁冲突:"+customerCode+"-"+warehouseCode+"-edbTradeGet", e);
//				}catch (Exception e) {
//					log.error("E店宝程序异常:"+customerCode+"-"+warehouseCode+"-edbTradeGet", e);
//				}
//				
//		} // end while
//	}
//	
//	/**
//	 * 查询交易订单
//	 * @param con
//	 * @param start
//	 * @param end
//	 * @throws Exception
//	 */
//	public void doSyncTrade(EdbTask edbTask,String page_no)throws Exception {
//		
//		String param = edbTask.getParam();
//		//log.info("E店宝应用参数："+param);
//		Map<String,String> paramMap = getParam(param);
//		Date startDate = edbTask.getStartTime();
//		Date endDate = edbTask.getEndTime();
//		paramMap.put("begin_time", TimeUtil.getNowDateString(startDate));
//		paramMap.put("end_time", TimeUtil.getNowDateString(endDate));
//		paramMap.put("page_no", page_no);
//		paramMap.put("page_size", edbTask.getPagesize());
//		int pagenum = Integer.parseInt(page_no);
//		String result = EdbAPITool.edbInterface(edbTask, paramMap);
//		JSONObject json = JSONObject.fromObject(result);
//		if(json.containsKey("Success"))
//		{
//			JSONObject Success = json.getJSONObject("Success");
//			JSONObject items = Success.getJSONObject("items");
//			int total_results = Success.getInt("total_results");
//			log.info(edbTask.getCustomerCode() + "E店宝订单："+total_results +"个");
//			JSONArray  item = items.getJSONArray("item");
//			if(total_results>0)
//			{
//				for(int i=0; i<item.size(); i++)
//				{
//					EdiOrder ediOrder=EdbAPITool.parseEdiOrder(item.get(i).toString());
//					ediOrder.setCustomerCode(edbTask.getCustomerCode());
//					ediOrder.setWarehouseCode(edbTask.getWarehouseCode());
//					ediOrder.setAreaGroupCode(edbTask.getWarehouseCode());
//					ediOrder.setErpType("edb");
//					ediOrder.setCrtime(new Date());
//					ShopSource shopSource = null;
//					shopSource = getShopSourceService().findShopName(ediOrder.getShopna());
//					if(null != shopSource)
//					{
//						ediOrder.setShopCode(shopSource.getShopCode());
//					}
//					else
//					{
//						ediOrder.setShopCode("edb_" + edbTask.getCustomerCode());
//					}
//					Area area = getAreaService().findByAreaName(ediOrder.getProvna());
//					if(null != area)
//					{
//						ediOrder.setProvco(area.getAreaCode());
//					}
//					getEdiOrderService().saveEdiOrderPlat(ediOrder);
//				}
//				pagenum++;
//				//edbTask.setPagenum(pagenum +"");
//				doSyncTrade(edbTask,pagenum+"");
//			}
//		}
//		else
//		{
//			log.error("E店宝订单拉取失败："+result +": "+TimeUtil.getNowDateString(startDate)+"-"+TimeUtil.getNowDateString(endDate)+" |pageSize:"+ edbTask.getPagesize()+"|pageNo:"+ page_no);
//		} 
//	}
//	
//	public Map<String,String> getParam(String param)
//	{
//		TreeMap<String, String> map = new TreeMap<String, String>();
//		if("".equals(param) || param == null)
//		{
//			return map;
//		}
//		String[] entrys = param.split("::");
//		for(String entry : entrys)
//		{
//			String[] p = entry.split("#");
//			map.put(p[0], p[1]);
//		}
//		return map;
//	}
//	public void setFlag(boolean flag) {
//		this.flag = flag;
//	}
//	ApplicationContext applicationContext;
//	@Override
//	public void setApplicationContext(ApplicationContext arg0)
//			throws BeansException {
//		applicationContext = arg0;
//		
//	}
//
//	public ApplicationContext getApplicationContext() {
//		return applicationContext;
//	}
//}
